<template>
    <div class="jieyue-form">
        <div class="page-header">
            <router-link to="/main/renshi/zhaoping/zhaopingxiudin" class="back-link">
                <i class="el-icon-arrow-left"></i>返回
            </router-link>
            <h2>文件借阅登记表</h2>
        </div>

        <div v-for="(form, index) in formList" :key="index" class="form-container">
            <div class="form-header">
                <h1>深圳市艾美思普科技有限公司 文件借阅登记表</h1>
                <div class="form-index">第 {{ index + 1 }} 条记录</div>
                <el-button 
                    v-if="formList.length > 1" 
                    type="danger" 
                    size="small" 
                    icon="el-icon-delete"
                    class="delete-form-btn"
                    @click="removeForm(index)">
                    删除
                </el-button>
            </div>

            <div class="form-section">
                <el-form
                    :ref="'form' + index"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                    :disabled="isView">
                    
                    <el-form-item
                        label="文件编号"
                        prop="fileNumber"
                        :rules="rules.fileNumber">
                        <el-input v-model="form.fileNumber" placeholder="请输入文件编号"></el-input>
                    </el-form-item>

                    <el-form-item
                        label="文件名称"
                        prop="fileName"
                        :rules="rules.fileName">
                        <el-input v-model="form.fileName" placeholder="请输入文件名称"></el-input>
                    </el-form-item>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item
                                label="版本"
                                prop="fileVersion"
                                :rules="rules.fileVersion">
                                <el-input v-model="form.fileVersion" placeholder="请输入版本号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="借阅数量"
                                prop="borrowQuantity"
                                :rules="rules.borrowQuantity">
                                <el-input-number
                                    v-model="form.borrowQuantity"
                                    :min="1"
                                    :max="999"
                                    controls-position="right"
                                    style="width: 100%">
                                </el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item
                                label="借阅者签名"
                                prop="borrowerSignature"
                                :rules="rules.borrowerSignature">
                                <el-input v-model="form.borrowerSignature" placeholder="请输入借阅者签名"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="借阅日期"
                                prop="borrowDate"
                                :rules="rules.borrowDate">
                                <el-date-picker
                                    v-model="form.borrowDate"
                                    type="datetime"
                                    placeholder="请选择借阅日期"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    style="width: 100%">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item
                                label="归还者签名"
                                prop="returnerSignature">
                                <el-input v-model="form.returnerSignature" placeholder="请输入归还者签名"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="归还日期"
                                prop="returnDate">
                                <el-date-picker
                                    v-model="form.returnDate"
                                    type="datetime"
                                    placeholder="请选择归还日期"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    style="width: 100%">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="备注" prop="remark">
                        <el-input
                            type="textarea"
                            v-model="form.remark"
                            :rows="3"
                            placeholder="请输入备注信息">
                        </el-input>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <div class="form-footer">
            <p class="form-info">表单编号及版本：AM - FR - 0010 A/0 生效日期：2006年11月1日 保存年限:长期</p>
            <div class="form-actions" v-if="!isView">
                <el-button @click="$router.push('/main/biao/jieyueList')">取消</el-button>
                <el-button type="primary" @click="handleSubmit">批量保存</el-button>
                <el-button type="success" @click="handleAdd">继续新增</el-button>
                <el-button type="primary" @click="goToList">列表</el-button>    
            </div>
        </div>
    </div>
</template>

<script>
import { getFileBorrowById, saveFileBorrow } from '@/api/fileBorrow'
import dayjs from 'dayjs'
import {formatDateTime,formatDate} from '@/utils/date'

export default {
    name: 'Jieyue',
    data() {
        return {
            formList: [{
                id: null,
                fileNumber: '',
                fileName: '',
                fileVersion: '',
                borrowQuantity: 1,
                borrowerSignature: '',
                borrowDate: '',
                returnerSignature: '',
                returnDate: '',
                remark: ''
            }],
            borrowDateOptions: {
                shortcuts: [
                    {
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date())
                        }
                    },
                    {
                        text: '明天',
                        onClick(picker) {
                            const date = new Date()
                            date.setTime(date.getTime() + 3600 * 1000 * 24)
                            picker.$emit('pick', formatDate(date))
                        }
                    },
                    {
                        text: '一周后',
                        onClick(picker) {
                            const date = new Date()
                            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
                            picker.$emit('pick', formatDate(date))
                        }
                    }
                ]
            },
            returnDateOptions: {
                shortcuts: [
                    {
                        text: '一周后',
                        onClick(picker) {
                            const date = new Date()
                            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
                            picker.$emit('pick', formatDate(date))
                        }
                    },
                    {
                        text: '两周后',
                        onClick(picker) {
                            const date = new Date()
                            date.setTime(date.getTime() + 3600 * 1000 * 24 * 14)
                            picker.$emit('pick', formatDate(date))
                        }
                    },
                    {
                        text: '一个月后',
                        onClick(picker) {
                            const date = new Date()
                            date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
                            picker.$emit('pick', formatDate(date))
                        }
                    }
                ]
            },
            rules: {
                fileNumber: [
                    { required: true, message: '请输入文件编号', trigger: 'blur' }
                ],
                fileName: [
                    { required: true, message: '请输入文件名称', trigger: 'blur' }
                ],
                fileVersion: [
                    { required: true, message: '请输入版本', trigger: 'blur' }
                ],
                borrowQuantity: [
                    { required: true, message: '请输入借阅数量', trigger: 'blur' },
                    { type: 'number', message: '借阅数量必须为数字', trigger: 'blur' }
                ],
                borrowerSignature: [
                    { required: true, message: '请输入借阅者签名', trigger: 'blur' }
                ],
                borrowDate: [
                    { required: true, message: '请选择借阅日期', trigger: 'change' }
                ],
                returnDate: [
                    { validator: this.validateReturnDate, trigger: 'change' }
                ]
            }
        }
    },
    computed: {
        isView() {
            return this.$route.query.mode === 'view'
        }
    },
    created() {
        const id = this.$route.query.id
        if (id) {
            this.loadData(id)
        }
    },
    methods: {
        goToList() {
            this.$router.push('/main/biao/jieyueList')
        },  
        async loadData(id) {
            try {
                const res = await getFileBorrowById(id)
                if (res.data) {
                    this.formList = [{
                        ...res.data,
                        borrowDate: res.data.borrowDate ? formatDateTime(res.data.borrowDate) : '',
                        returnDate: res.data.returnDate ? formatDateTime(res.data.returnDate) : ''
                    }]
                }
            } catch (error) {
                console.error('加载数据错误:', error)
                this.$message.error('加载数据失败')
            }
        },
        async handleSubmit() {
            try {
                // 验证所有表单
                const formRefs = this.formList.map((_, index) => this.$refs['form' + index])
                const validateResults = await Promise.all(
                    formRefs.map(formRef => formRef[0].validate().catch(() => false))
                )

                if (validateResults.includes(false)) {
                    this.$message.warning('请完善所有表单的必填信息')
                    return
                }

                // 批量保存
                await saveFileBorrow(this.formList)
                this.$message.success('批量保存成功')
                this.$router.push('/main/biao/jieyueList')
            } catch (error) {
                console.error('保存错误:', error)
                this.$message.error('保存失败')
            }
        },
        disablePastDates(time) {
            return time.getTime() < Date.now() - 8.64e7 // 禁用昨天及以前的日期
        },
        disableInvalidReturnDates(time) {
            if (!this.formList[0].borrowDate) return false
            const borrowDate = new Date(this.formList[0].borrowDate)
            return time.getTime() < borrowDate.getTime() // 禁用早于借阅日期的日期
        },
        validateReturnDate(rule, value, callback) {
            if (!value) {
                callback()
                return
            }
            if (!this.formList[0].borrowDate) {
                callback(new Error('请先选择借阅日期'))
                return
            }
            const borrowDate = new Date(this.formList[0].borrowDate)
            const returnDate = new Date(value)
            if (returnDate < borrowDate) {
                callback(new Error('归还日期不能早于借阅日期'))
                return
            }
            callback()
        },
        formatDate(date) {
            if (!date) return ''
            const d = new Date(date)
            if (isNaN(d.getTime())) return date
            return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
        },
        resetForm() {
            this.formList = [{
                id: null,
                fileNumber: '',
                fileName: '',
                fileVersion: '',
                borrowQuantity: 1,
                borrowerSignature: '',
                borrowDate: '',
                returnerSignature: '',
                returnDate: '',
                remark: ''
            }]
            this.$refs.form.clearValidate()
        },
        async handleAdd() {
            const newForm = {
                id: null,
                fileNumber: '',
                fileName: '',
                fileVersion: '',
                borrowQuantity: 1,
                borrowerSignature: '',
                borrowDate: '',
                returnerSignature: '',
                returnDate: '',
                remark: ''
            }
            this.formList.push(newForm)
        },
        removeForm(index) {
            if (this.formList.length > 1) {
                this.formList.splice(index, 1)
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.jieyue-form {
    padding: 20px;
    // background-color: #f5f7fa;
    min-height: calc(100vh - 40px);

    .page-header {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        background-color: #fff;
        padding: 16px 24px;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

        .back-link {
            color: #409EFF;
            text-decoration: none;
            margin-right: 20px;
            display: flex;
            align-items: center;
            font-size: 14px;
            transition: all 0.3s;

            &:hover {
                opacity: 0.8;
            }

            i {
                margin-right: 5px;
            }
        }

        h2 {
            margin: 0;
            font-size: 20px;
            font-weight: 500;
            color: #303133;
        }
    }

    .form-container {
        background-color: #fff;
        padding: 32px;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        margin-bottom: 20px;

        .form-header {
            position: relative;
            
            .form-index {
                position: absolute;
                top: 0;
                left: 0;
                background-color: #409EFF;
                color: #fff;
                padding: 4px 12px;
                border-radius: 4px;
                font-size: 14px;
            }

            .delete-form-btn {
                position: absolute;
                top: 0;
                right: 0;
                padding: 5px 10px;
            }
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: #606266;
            padding-right: 20px;
        }

        :deep(.el-input__inner) {
            border-radius: 4px;
            transition: all 0.3s;
            &:hover, &:focus {
                border-color: #409EFF;
            }
        }

        :deep(.el-textarea__inner) {
            border-radius: 4px;
            min-height: 80px;
            transition: all 0.3s;
            &:hover, &:focus {
                border-color: #409EFF;
            }
        }

        :deep(.el-date-editor) {
            width: 100%;
            .el-input__inner {
                padding-left: 40px;
            }
            .el-range-separator {
                padding: 0 5px;
            }
            &.el-date-editor--datetime {
                .el-range-input {
                    width: 42%;
                }
            }
            .el-picker-panel__shortcut {
                color: #409EFF;
                &:hover {
                    color: #66b1ff;
                }
            }
        }
    }

    .form-footer {
        border-top: 1px solid #EBEEF5;
        padding-top: 24px;
        margin-top: 40px;

        .form-info {
            text-align: center;
            color: #909399;
            font-size: 14px;
            margin-bottom: 24px;
            background-color: #f5f7fa;
            padding: 12px;
            border-radius: 4px;
            line-height: 1.6;
        }

        .form-actions {
            display: flex;
            justify-content: center;
            gap: 16px;

            .el-button {
                min-width: 100px;
                padding: 12px 16px;
                font-size: 14px;
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }

                &:not(:last-child) {
                    margin-right: 12px;
                }
            }
        }
    }

    @media screen and (max-width: 768px) {
        padding: 12px;

        .page-header {
            padding: 12px 16px;
        }

        .form-container {
            margin-bottom: 16px;
            padding: 20px 16px;

            .form-header {
                .form-index {
                    position: relative;
                    display: inline-block;
                    margin-bottom: 10px;
                }

                .delete-form-btn {
                    position: relative;
                    margin-top: 10px;
                }
            }
        }

        .form-footer {
            .form-actions {
                flex-direction: column;
                gap: 12px;

                .el-button {
                    width: 100%;
                    margin-right: 0 !important;
                }
            }
        }
    }
}
</style>